<template>
	<view class="main">
		<topCommonTitleBar class="topBar" :statePerchHeight="'var(--status-bar-height)'" arrow="black" dot-color="#333"
			:show-dot="true" title="文档详情" titleColor="#000" @actionClick="showMore = true;" backgroundColor="#fff" />
		<swiper class="swiper" :indicator-dots="false" :current="imgIndex" :duration="300"
			:disable-programmatic-animation="true" @change="onSwiperChange">
			<swiper-item class="swiper_item" v-for="(item, index) in picList" :key="index">
				<image class="img" :src="item" mode="scaleToFill" />
			</swiper-item>
		</swiper>
		<view class="imgNum">{{ imgIndex + 1 }}/{{ picList.length }}</view>
		<view class="content">
			<view class="download_con">
				<view class="title flex">
					<image src="/static/img/template/pdf.png" class="title_icon mr20" mode="" v-if="templateDetails.type == 'pdf'">
					</image>
					<image src="/static/img/template/wd.png" class="title_icon mr20" mode="" v-if="templateDetails.type == 'WORD'">
					</image>
					<image src="/static/img/template/excel.png" class="title_icon mr20" mode=""
						v-if="templateDetails.type == 'EXCEL'">
					</image>
					<image src="/static/img/template/ppt.png" class="title_icon mr20" mode="" v-if="templateDetails.type == 'PPT'">
					</image>
					<image src="/static/img/template/zip.png" class="title_icon mr20" mode="" v-if="templateDetails.type == 'ZIP'">
					</image>
					<view class="tit">
						{{ templateDetails.title }}
					</view>
				</view>
				<view class="download_info flex_between">
					<view class="down_num flex_align">
						<u-icon name="download" size="20" color="#9E9E9E"></u-icon>
						{{ templateDetails.download }}
					</view>
					<view class="leaf flex_align" v-if="templateDetails.money > 0">
						<image class="leaf_icon" src="/static/img/template/leaf.png" mode="scaleToFill" />
						<text class="money">{{ templateDetails.money }}</text>
					</view>
					<view class="free" v-if="templateDetails.money == 0">免费下载</view>
				</view>
			</view>
			<view class="download_con file flex_wrap">
				<view class="detail">文件格式：{{ templateDetails.type }}</view>
				<view class="detail">文件类型：{{ templateDetails.tname }}</view>
				<view class="detail">上传时间：{{ templateDetails.push_date }}</view>
				<view class="detail">文件来源：{{ templateDetails.resource }}</view>
			</view>
		</view>
		<view class="footer flex_between_center">
			<view class="collect flex_col_center" @click="collect">
				<image class="collect_icon" v-if="templateDetails.is_collect == 0" src="/static/img/wenTiKu/collect_0.png"
					mode="scaleToFill" />
				<image class="collect_icon" v-else src="/static/img/wenTiKu/collect_1.png" mode="scaleToFill" />
				{{ templateDetails.is_collect == 0 ? '收藏' : '取消收藏' }}
			</view>

			<view class="flex download"
				v-if="isPay == false && isVip == false && templateDetails.money > 0 && templateDetails.is_downnload == 0">
				<view class="bottomLeft footer_txt" @click="showPay = true">
					<text class="mt10">原价购买</text> <br>
					<span class="payNum">（{{ templateDetails.money }}片小竹叶）</span>
				</view>
				<view class="bottomRight footer_txt" @click="goRecharge()">会员下载 <br>
					<text class="vip">成为会员免费下载</text>
				</view>
			</view>
			<view class="vip_btn btn"
				v-if="!download && isVip == true && templateDetails.money > 0 && templateDetails.is_downnload == 0"
				@click="goDownload()">
				会员免费下载
			</view>
			<view class="downLoad_btn btn" v-if="!download && templateDetails.money == 0 && templateDetails.is_downnload == 0"
				@click="goDownload()">
				下载模板
			</view>
			<view class="downLoad_btn checkModel btn" style="background-color: #16CACA;" v-if="download"
				@click="previewDocument()">
				查看模板
			</view>
			<view class="downLoad_btn checkModel btn" style="background-color: #16CACA;"
				v-if="templateDetails.is_downnload && !download" @click="goDownload(1)">
				查看模板
			</view>
		</view>


		<!-- 支付小竹叶弹出层 -->
		<view v-show="showPay">
			<u-popup :show="showPay" :round="15" class="showPay" closeable @close="close">
				<view class="pay_title">
					支付小竹叶
				</view>
				<view class="middle_box flex">
					<image src="/static/img/template/leaf_green.png" mode="" class="pay_icon mr">
					</image>
					<text class="mr10">小竹叶</text>
					<text class="price_num">{{ templateDetails.money }}</text>
					<image src="/static/img/template/right.png" mode="" class="pay_icon"></image>
				</view>

				<view class="pay_bottom_box">
					当前小竹叶 {{ userInfo.money }}，<text class="goPay" @click="topUp()">去充值</text>
				</view>
				<view class="sure_bottom close" @click="payment">确定</view>
			</u-popup>
		</view>


		<!-- 更多弹出层 -->
		<view v-if="showMore">
			<u-popup :show="showMore" :round="15" class="showMore" @close="close" :closeOnClickOverlay="true"
				:customStyle="{ backgroundColor: 'transparent' }">
				<view class="moreItem flex_wrap_center_between">
					<view class="items mb20 flex_col_center" v-for="(item, index) in menuList" :key="index"
						@click="menuClick(item)">
						<image :src="item.icon" class="icon"></image>
						<text class="title">{{ item.name }}</text>
					</view>
				</view>
				<view class="close" @click="showMore = false">取消</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
import { getModelInfo, setCollect, payModel } from '@/api/template.js'
import { getUserInfo } from '@/api/my.js'
export default {
	data() {
		return {
			id: '',
			showMore: false,//更多菜单
			userInfo: {},//用户信息
			menuList: [{
				icon: '/static/img/wenTiKu/wx.png',
				name: '微信好友',
				remark: '',
				url: '',
				handler: 'shareTo'
			},
			{
				icon: '/static/img/wenTiKu/pyq.png',
				name: '朋友圈',
				remark: '',
				url: '',
				handler: 'shareToMoments'
			},
			{
				icon: '/static/img/wenTiKu/qq.png',
				name: 'QQ好友',
				remark: '',
				url: '',
				handler: 'toShareQq'
			},
			{
				icon: '/static/img/wenTiKu/copyLink.png',
				name: '复制链接',
				remark: '',
				url: '',
				handler: 'copyLink'
			},
			{
				icon: '/static/img/wenTiKu/collect_0.png',
				name: '收藏',
				remark: '',
				url: '',
				handler: 'collect'
			}],//更多菜单
			templateDetails: {},//模板详情
			isVip: '', //是否是VIP
			isPay: '',	//是否付费
			download: '',//是否下载
			showPay: false,//付费弹层
			picList: [],//图片列表
			imgIndex: 0,//图片下标
			downloadUrl: '',//下载地址
		};
	},
	methods: {
		//请求模板详情
		getTemplateDetails() {
			getModelInfo({
				id: this.id
			}).then(res => {
				console.log(res.data.is_collect);
				if (res.code == 1) {
					this.templateDetails = res.data
					if (res.data.images) {
						this.picList = res.data.images.split('|')
					}
					this.downloadUrl = res.data.content
					uni.setStorageSync("downloadUrl", this.downloadUrl)
					if (this.templateDetails.is_collect == 0) {
						this.menuList[4] = {
							icon: '/static/img/wenTiKu/collect_0.png',
							name: '收藏',
							handler: 'collect'
						}
					} else if (this.templateDetails.is_collect == 1) {
						this.menuList[4] = {
							icon: '/static/img/wenTiKu/collect_1.png',
							name: '取消收藏',
							handler: 'collect'
						}
					}
					if (this.templateDetails.is_downnload == 0) {
						this.isPay = false
					} else {
						this.isPay = true
					}
					this.isDownload()
				}
			})
		},

		//获取用户信息
		getUserInfo() {
			getUserInfo().then(res => {
				this.userInfo = res.data
				if (res.data.is_vip == 0) {
					this.isVip = false
				} else {
					this.isVip = true
				}
			})
		},

		//swiper切换
		onSwiperChange(e) {
			this.imgIndex = e.detail.current
		},

		//收藏切换
		collect() {
			setCollect({
				cid: this.id
			}).then(res => {
				if (res.code == 1) {
					//收藏和未收藏切换
					this.templateDetails.is_collect = 1 - this.templateDetails.is_collect
					this.menuList[4].icon = `/static/img/wenTiKu/collect_${this.templateDetails.is_collect}.png`
					if (this.templateDetails.is_collect == 1) {
						this.menuList[4].name = '取消收藏'
						this.$tools.showToast("收藏成功");
					} else if (this.templateDetails.is_collect == 0) {
						this.$tools.showToast("取消收藏");
						this.menuList[4].name = '收藏'
					}
					this.getModelInfo()
				}
			})
		},
		//去充值小竹叶
		topUp() {
			uni.navigateTo({ url: '/pages/my/bambooLeaf/recharge' })
		},
		//去成为会员
		goRecharge() {
			uni.navigateTo({ url: '/pages/my/vip/index' })
		},

		//支付
		payment() {
			payModel({ id: this.id }).then(res => {
				if (res.code == 1) {
					this.$tools.showToast("支付成功");
					this.goDownload()
					this.userInfo = uni.getStorageSync('userInfo') || {}
					this.showPay = false
					this.getUserInfo()
					this.getTemplateDetails()
				} else {
					this.$tools.showToast(res.msg);
				}
			})
		},

		//不需要支付小竹叶时也要传递下载的模板id,进行保存id
		downModel() {
			payModel({ id: this.id }).then(res => {
				if (res.code == 1) {
					this.userInfo = uni.getStorageSync('userInfo') || {}
				} else {
					this.$tools.showToast(res.msg);
				}
			})
		},

		//关闭支付弹窗
		close() {
			this.showPay = false
			this.showMore = false
		},

		//下载
		goDownload(e) {
			var that = this
			uni.downloadFile({
				url: this.downloadUrl, //下载地址接口返回
				success: (data) => {
					if (data.statusCode === 200) {
						//文件保存到本地
						uni.saveFile({
							tempFilePath: data.tempFilePath, //临时路径
							success: function (res) {
								uni.showToast({
									icon: 'none',
									mask: true,
									title: '文件下载成功', //保存路径  res.savedFilePath
									duration: 3000,
								});
								let cacheList = uni.getStorageSync('modelFileCache')
								if (cacheList == null ||
									cacheList == undefined ||
									cacheList == '') {
									cacheList = []
									uni.setStorageSync('modelFileCache', [])
								}

								for (let i = 0; i < cacheList.length; i++) {
									if (cacheList[i].netUrl == that.downloadUrl) {
										cacheList.splice(cacheList[i], 1)
										break
									}
								}
								// 保存本次数据
								let saveData = {
									netUrl: that.downloadUrl,
									localPath: res.savedFilePath,
									modelId: that.id,
									name: that.templateDetails.title
								}
								cacheList.push(saveData)
								uni.setStorageSync('modelFileCache', cacheList)
								that.getTemplateDetails()
								that.downModel()
								//下载被清缓存，重新下载，查看模板
								if (e == 1) {
									that.previewDocument()
								}
							}
						});
					}
				},
				fail: (err) => {
					console.log(err);
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '失败，请重新下载',
					});
				},
			});
		},
		//判断是否下载
		isDownload() {
			let cacheList = uni.getStorageSync("modelFileCache")
			if (cacheList == null) {
				cacheList = []
				uni.setStorageSync("modelFileCache", [])
			}
			let hasDownload = false //是否被下载
			for (let i = 0; i < cacheList.length; i++) {
				if (cacheList[i].netUrl == this.downloadUrl) {
					if (cacheList[i].localPath != null &&
						cacheList[i].localPath != "" &&
						cacheList[i].localPath != undefined) {
						hasDownload = true
					}
					break
				}
			}
			console.log('hasDownload', hasDownload);
			this.download = hasDownload
		},

		//查看模板
		previewDocument() {
			let cacheList = uni.getStorageSync("modelFileCache")
			if (cacheList == null) {
				cacheList = []
				uni.setStorageSync("modelFileCache", [])
			}
			for (let i = 0; i < cacheList.length; i++) {
				if (cacheList[i].netUrl == this.downloadUrl) {
					if (cacheList[i].localPath != null &&
						cacheList[i].localPath != "" &&
						cacheList[i].localPath != undefined) {
						uni.openDocument({
							filePath: cacheList[i].localPath
						});
					}
					break
				}
			}
		},

		//更多弹窗点击事件
		menuClick(e) {
			if (e.handler) {
				this[e.handler]()
			} else if (e.url) {
				this.$used.href(e.url)
			}
		},

		//分享到微信好友
		shareTo() {
			var share_url = this.$h5Url.server + '/pages/details/modelInfo?id=' + this.id

			uni.share({
				provider: "weixin",
				scene: "WXSceneSession",
				type: 0,
				href: share_url,
				title: this.templateDetails.title,
				summary: this.templateDetails.tname,
				imageUrl: "/static/logo-min.png",
				success: function (res) {
					if (callback != null) {
						callback()
					}
					this.showMore = false
				},
				fail: function (err) {
					console.log("fail:" + JSON.stringify(err));
				}
			});
		},
		//分享到微信朋友圈
		shareToTimeline() {
			var share_url = this.$h5Url.server + '/pages/details/modelInfo?id=' + this.id
			uni.share({
				provider: "weixin",
				scene: "WXSceneTimeline",
				type: 0,
				href: share_url,
				title: this.templateDetails.title,
				summary: this.templateDetails.tname,
				imageUrl: "/static/logo-min.png",
				success: function (res) {
					if (callback != null) {
						callback()
					}
					this.showMore = false
				},
				fail: function (err) {
					console.log("fail:" + JSON.stringify(err));
				}
			});
		},
		// 分享到qq
		toShareQq() {
			var share_url = this.$h5Url.server + '/pages/details/modelInfo?id=' + this.id

			uni.share({
				provider: "qq",
				scene: "WXSceneSession",
				type: 0,
				href: share_url,
				title: this.templateDetails.title,
				summary: this.templateDetails.tname,
				imageUrl: "/static/logo-min.png",
				success: function (res) {

					if (callback != null) {
						callback()
					}
					this.showMore = false
				},
				fail: function (err) {
					console.log("fail:" + JSON.stringify(err));
				}
			});
		},

		//复制链接
		copyLink() {
			let _that = this
			uni.setClipboardData({
				data: _that.$h5Url.server + '/pages/details/modelInfo?id=' + this.id,
				success: function () {
					uni.showToast({
						title: '链接复制成功'
					})
					_that.showMore = false
					uni.showToast({
						title: '链接复制成功'
					})
				}
			});
		},

	},
	onLoad(e) {
		let { id } = e
		console.log(e);
		this.id = id
		this.getTemplateDetails()
		this.getUserInfo()
	},
}
</script>

<style lang="scss">
.main {
	background-color: #F6F6F6;

	.topBar {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99999;
	}


	.swiper {
		margin-top: calc(var(--status-bar-height) + 88rpx);
		width: 100%;
		height: 691rpx !important;

		.swiper_item {
			.img {
				display: block;
				position: relative;
				margin: 0 auto;
				width: 502rpx !important;
				height: 691rpx !important;
			}
		}
	}

	.imgNum {
		padding: 0 10rpx;
		position: absolute;
		top: 30rpx;
		right: 130rpx;
		text-align: center;
		height: 37rpx;
		font-size: 26rpx;
		line-height: 37rpx;
		background: #B9B9B9;
		border-radius: 76rpx;
		color: #fff;
	}

	.content {
		padding: 30rpx;
		box-sizing: border-box;

		.download_con {
			background: #fff;
			padding: 30rpx;
			margin: 30rpx auto;
			width: 690rpx;
			border-radius: 10rpx;

			.title {
				font-size: 32rpx;
				line-height: 44rpx;

				.title_icon {
					width: 40rpx;
					height: 40rpx;
				}

				.tit {
					width: 586rpx !important;
				}
			}

			.download_info {
				margin-top: 40rpx;

				.down_num {
					color: #9E9E9E;
				}

				.leaf {
					.leaf_icon {
						width: 20rpx;
						height: 30rpx;
					}

					.money {
						margin-left: 10rpx;
						font-size: 36rpx;
						color: #FF5900;
					}
				}

				.free {
					font-size: 26rpx;
					color: #999999;
				}
			}

		}

		.file {
			margin-top: 40rpx;
			flex-direction: row;
			justify-content: space-between;
			font-size: 28rpx;

			.detail {
				min-width: 312rpx;
				margin: 20rpx 0;
			}
		}

	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
		background: #fff;
		padding: 30rpx 30rpx 0 30rpx;

		.collect {
			width: 112rpx;
			font-size: 26rpx;
		}

		.collect_icon {
			width: 48rpx;
			height: 48rpx;
		}

		.download {

			.footer_txt {
				padding: 10rpx 0;
				text-align: center;
				width: 263rpx;
				height: 90rpx;
				line-height: 32rpx;

			}

			.bottomLeft {
				color: #fff;
				background: linear-gradient(90deg, #F75E3C 0%, #FE4F3C 100%);
				border-radius: 86rpx 0rpx 0rpx 86rpx;

				.payNum {
					font-size: 20rpx;
					color: #fff;
				}
			}

			.bottomRight {
				color: #7E5712;
				background: linear-gradient(90deg, #FADEAE 0%, #EFC386 100%);
				border-radius: 0rpx 86rpx 86rpx 0rpx;

				.vip {
					font-size: 20rpx;
					color: #7E5712;
				}
			}
		}

		.vip_btn {
			color: #7E5712;
			background: linear-gradient(90deg, #FADEAE 0%, #EFC386 100%);
			border-radius: 86rpx;
		}

		.downLoad_btn {
			color: #fff;
			background: #1C87F3;
			border-radius: 132rpx;
		}

		.btn {
			text-align: center;
			width: 500rpx;
			height: 90rpx;
			line-height: 90rpx;
		}
	}

	.showPay {
		.pay_title {
			padding: 50rpx;
			padding-top: 30rpx;
			color: #333333;
			font-size: 32rpx;
		}

		.middle_box {
			padding: 0 50rpx;
			margin-bottom: 44rpx;
		}

		.pay_icon {
			vertical-align: bottom;
			width: 34rpx;
			height: 34rpx;
		}

		.price_num {
			margin-left: 10rpx;
			font-size: 36rpx;
			color: #FF5900;
			margin-right: 354rpx;
		}

		.pay_bottom_box {
			border-top: 1rpx solid #E2E2E2;
			padding: 25rpx 50rpx;
			width: 100%;
			height: 145rpx;
			color: #666666;
			font-size: 28rpx;
		}

		.goPay {
			color: #1C87F3;
			text-decoration: underline;
		}

		.sure_bottom {
			margin: 20rpx auto;
			text-align: center;
			width: 647rpx;
			height: 85rpx;
			line-height: 85rpx;
			background: #1C87F3;
			border-radius: 147rpx;
			color: #fff;
		}

		.checkModel {
			background-color: #16CACA;
		}
	}

	.showMore {
		text-align: center;

		.moreItem {
			padding: 34rpx 26rpx;
			box-sizing: border-box;
			width: 700rpx;
			margin: 12rpx auto;
			border-radius: 16rpx;
			background-color: #FFFFFF;

			.items {
				width: 162rpx;

				.icon {
					width: 87rpx;
					height: 85rpx;
				}

				.title {
					margin-top: 20rpx;
					font-size: 26rpx;
					color: #646566;
				}
			}
		}

		.close {
			width: 700rpx;
			height: 94rpx;
			margin: 12rpx auto 34rpx auto;
			text-align: center;
			line-height: 94rpx;
			background-color: #FFFFFF;
			border-radius: 16rpx;
		}
	}
}
</style>
